
from django import forms
from django.contrib.auth.hashers import check_password, make_password

from common.models import User


class UserRegisterForm(forms.Form):
    mobile = forms.CharField(required=True, max_length=11, min_length=11,
                            error_messages={
                                # 'required': '必须填写手机号',
                                'max_length': '请填写正确手机号',
                                'min_length': '请填写正确手机号',
                            })
    password = forms.CharField(required=True, max_length=8, min_length=6,
                               error_messages={
                                   # 'required': '请填写密码',
                                   'max_length': '密码至多8位',
                                   'min_length': '密码至少6位',
                               })
    password2 = forms.CharField(required=True, max_length=8, min_length=6,
                               error_messages={
                                   # 'required': '请填写密码',
                                   'max_length': '密码至多8位',
                                   'min_length': '密码至少6位',
                               })

    def clean_mobile(self):
        # 校验表单数据
        user = User.objects.filter(phone=self.cleaned_data.get('mobile')).first()
        if user:
            raise forms.ValidationError('该用户已存在，请重新注册')
        # 这里一定要返回self.cleand_data['mobile']，不然数据就传不到下面，也不会到视图函数那里。
        return self.cleaned_data['mobile']

    def clean(self):
        pwd = self.cleaned_data.get('password')
        pwd2 = self.cleaned_data.get('password2')
        if pwd != pwd2:
            raise forms.ValidationError({'password2': '两次密码不一致'})
        # 密码正确，对密码加密
        secret_pwd = make_password(pwd)
        self.cleaned_data['password'] = secret_pwd
        return self.cleaned_data


class UserLoginForm(forms.Form):
    mobile = forms.CharField(required=True, max_length=11, min_length=11,
                            error_messages={
                                # 'required': '必须填写手机号',
                                'max_length': '请填写正确手机号',
                                'min_length': '请填写正确手机号',
                            })
    password = forms.CharField(required=True, max_length=8, min_length=6,
                               error_messages={
                                   # 'required': '请填写密码',
                                   'max_length': '密码至多8位',
                                   'min_length': '密码至少6位',
                               })

    def clean(self):
        user = User.objects.filter(phone=self.cleaned_data.get('mobile')).first()
        if not user:
            raise forms.ValidationError({'mobile': '该用户不存在，请前往注册'})
        if not check_password(self.cleaned_data.get('password'), user.secret_pwd):
            raise forms.ValidationError({'password': '密码错误，请重新输入'})
        self.cleaned_data['user'] = user
        return self.cleaned_data



